<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧工单模板区域 -->
      <el-col :span="6">
        <el-card>
          <el-button type="primary" @click="showTemplateDialog('add')">
            <el-icon>
              <Plus />
            </el-icon>新建模板
          </el-button>

          <el-input class="mt-2" size="large" v-model="templateQuery.templateName" placeholder="搜索模板名称" clearable
            @keyup.enter="fetchTemplates" />

          <el-scrollbar class="template-scroll mt-2">
            <div v-for="template in templateList" :key="template.templateId" class="template-item"
              :class="[activeTemplateId == template.templateId ? 'active' : '']"
              @click="handleTemplateSelect(template)">
              <div class="template-name">{{ template.templateName }}</div>
              <div>
                <el-button type="text" @click="showTemplateDialog('edit', template)">编辑</el-button>
                <el-button type="text" @click="deleteTemplate(template.id)">删除</el-button>
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 右侧流转环节配置区域 -->
      <el-col :span="18">
        <el-card>
          <div class="section-title">流转环节配置</div>
          <el-row :gutter="10" class="mb-2">
            <el-col :span="24" style="text-align: right;">
              <el-button type="primary" @click="showStepDialog('add')" :disabled="!currentTemplate">
                <el-icon>
                  <Plus />
                </el-icon>新增环节
              </el-button>
            </el-col>
          </el-row>

          <el-table :data="stepList" border v-loading="stepLoading">
            <el-table-column prop="stepName" label="环节名称" width="120" />
            <el-table-column prop="nodeContent" label="节点内容" />
            <el-table-column prop="assigneeType" label="经办人类型" width="120" />
            <el-table-column prop="assigneeValue" label="经办人" width="120" />
            <el-table-column prop="timeLimit" label="时效(小时)" width="100" />
            <el-table-column prop="isRequired" label="是否必填" width="100">
              <template #default="{ row }">
                <el-tag :type="row.isRequired === 1 ? 'success' : 'info'">
                  {{ row.isRequired === 1 ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template #default="{ row, $index }">
                <el-button size="small" @click="showStepDialog('edit', row, $index)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteStep(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 工单模板对话框 -->
    <el-dialog v-model="templateDialog.visible" :title="templateDialog.title" width="500px">
      <el-form ref="templateFormRef" :model="templateForm" :rules="templateRules" label-width="80px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="templateForm.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="templateForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="templateDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitTemplateForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 流转环节配置对话框 -->
    <el-dialog v-model="stepDialog.visible" :title="stepDialog.title" width="600px">
      <el-form ref="stepFormRef" :model="stepForm" :rules="stepRules" label-width="100px">
        <el-form-item label="环节名称" prop="stepName">
          <el-input v-model="stepForm.stepName" placeholder="请输入环节名称" />
        </el-form-item>
        <el-form-item label="节点内容" prop="nodeContent">
          <el-input v-model="stepForm.nodeContent" type="textarea" :rows="3" placeholder="请输入节点内容" />
        </el-form-item>
        <el-form-item label="经办人类型" prop="assigneeType">
          <el-select v-model="stepForm.assigneeType" placeholder="请选择经办人类型" @change="handleAssigneeTypeChange">
            <el-option v-for="item in operatorTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="经办人" prop="assigneeValue">
          <el-input v-model="stepForm.assigneeValue" placeholder="请输入经办人" />
        </el-form-item>
        <el-form-item label="时效(小时)" prop="timeLimit">
          <el-input-number v-model="stepForm.timeLimit" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="是否必填" prop="isRequired">
          <el-radio-group v-model="stepForm.isRequired">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="stepDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitStepForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Scrollbar from '@/components/Scrollbar'
import {
  listWorkOrderTemplate,
  addWorkOrderTemplate,
  updateWorkOrderTemplate,
  deleteWorkOrderTemplate,
  getOperatorTypeList,
  listWorkflowStep,
  addWorkflowStep,
  updateWorkflowStep,
  deleteWorkflowStep
} from '@/api/prod_operate/sys_setting/work_order/order_template'
const activeTemplateId = ref('')
// 左侧工单模板相关数据
const templateQuery = reactive({
  templateName: ''
})
const templateList = ref([])
const templateLoading = ref(false)
const currentTemplate = ref(null)

// 右侧流转环节配置相关数据
const stepList = ref([])
const stepLoading = ref(false)
const operatorTypeOptions = ref([])

// 工单模板对话框
const templateDialog = reactive({
  visible: false,
  title: '',
  mode: 'add' // add/edit
})
const templateForm = reactive({
  templateId: undefined,
  templateName: '',
  remark: ''
})
const templateFormRef = ref()
const templateRules = reactive({
  templateName: [
    { required: true, message: '请输入模板名称', trigger: 'blur' }
  ]
})

// 流转环节配置对话框
const stepDialog = reactive({
  visible: false,
  title: '',
  mode: 'add', // add/edit
  editIndex: -1
})
const stepForm = reactive({
  id: undefined,
  templateId: undefined,
  stepName: '',
  nodeContent: '',
  assigneeType: '',
  assigneeValue: '',
  timeLimit: 24,
  isRequired: 1
})
const stepFormRef = ref()
const stepRules = reactive({
  stepName: [
    { required: true, message: '请输入环节名称', trigger: 'blur' }
  ],
  nodeContent: [
    { required: true, message: '请输入节点内容', trigger: 'blur' }
  ],
  assigneeType: [
    { required: true, message: '请选择经办人类型', trigger: 'change' }
  ],
  assigneeValue: [
    { required: true, message: '请输入经办人', trigger: 'blur' }
  ],
  timeLimit: [
    { required: true, message: '请输入时效', trigger: 'blur' }
  ]
})

// 生命周期钩子
onMounted(() => {
  fetchTemplates()
  fetchOperatorTypes()
})

// 获取工单模板列表
const fetchTemplates = async () => {
  try {
    templateLoading.value = true
    const res = await listWorkOrderTemplate(templateQuery)
    templateList.value = res.rows

    handleTemplateSelect(templateList.value[0])
  } catch (error) {
    console.error('获取工单模板列表失败:', error)
    ElMessage.error('获取工单模板列表失败')
  } finally {
    templateLoading.value = false
  }
}

// 获取经办人类型下拉选项
const fetchOperatorTypes = async () => {
  try {
    const res = await getOperatorTypeList()
    operatorTypeOptions.value = res.data
  } catch (error) {
    console.error('获取经办人类型失败:', error)
    ElMessage.error('获取经办人类型失败')
  }
}

// 获取流转环节配置列表
const fetchWorkflowSteps = async (templateId) => {
  if (!templateId) return

  try {
    stepLoading.value = true
    const res = await listWorkflowStep({ templateId })
    stepList.value = res.rows
  } catch (error) {
    console.error('获取流转环节配置失败:', error)
    ElMessage.error('获取流转环节配置失败')
  } finally {
    stepLoading.value = false
  }
}

// 选择工单模板
const handleTemplateSelect = (template) => {
  currentTemplate.value = template
  activeTemplateId.value = template ? template.templateId : ''
  if (template) {
    fetchWorkflowSteps(template.templateId)
  } else {
    stepList.value = []
  }
}

// 显示工单模板对话框
const showTemplateDialog = (mode, row = null) => {
  templateDialog.mode = mode
  templateDialog.title = mode === 'add' ? '新建工单模板' : '编辑工单模板'
  templateDialog.visible = true

  if (mode === 'add') {
    templateForm.templateId = undefined
    templateForm.templateName = ''
    templateForm.remark = ''
  } else {
    templateForm.templateId = row.templateId
    templateForm.templateName = row.templateName
    templateForm.remark = row.remark || ''
  }
}

// 提交工单模板表单
const submitTemplateForm = async () => {
  try {
    await templateFormRef.value.validate()

    const isAdd = templateDialog.mode === 'add'
    const api = isAdd ? addWorkOrderTemplate : updateWorkOrderTemplate

    await api(templateForm)
    ElMessage.success('操作成功')
    templateDialog.visible = false
    fetchTemplates()
  } catch (error) {
    console.error('保存工单模板失败:', error)
  }
}

// 删除工单模板
const deleteTemplate = async (templateId) => {
  try {
    await ElMessageBox.confirm('确认删除该工单模板吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteWorkOrderTemplate(templateId)
    ElMessage.success('删除成功')
    fetchTemplates()

    // 如果删除的是当前选中的模板，清空右侧
    if (currentTemplate.value && currentTemplate.value.templateId === templateId) {
      currentTemplate.value = null
      stepList.value = []
    }
  } catch (error) {
    console.error('删除工单模板失败:', error)
  }
}

// 显示流转环节配置对话框
const showStepDialog = (mode, row = null, index = -1) => {
  if (!currentTemplate.value) {
    ElMessage.warning('请先选择工单模板')
    return
  }

  stepDialog.mode = mode
  stepDialog.title = mode === 'add' ? '新增流转环节' : '编辑流转环节'
  stepDialog.editIndex = index
  stepDialog.visible = true

  if (mode === 'add') {
    stepForm.id = undefined
    stepForm.templateId = currentTemplate.value.templateId
    stepForm.stepName = ''
    stepForm.nodeContent = ''
    stepForm.assigneeType = ''
    stepForm.assigneeValue = ''
    stepForm.timeLimit = 24
    stepForm.isRequired = 1
  } else {
    stepForm.id = row.id
    stepForm.templateId = row.templateId
    stepForm.stepName = row.stepName
    stepForm.nodeContent = row.nodeContent
    stepForm.assigneeType = row.assigneeType
    stepForm.assigneeValue = row.assigneeValue
    stepForm.timeLimit = row.timeLimit
    stepForm.isRequired = row.isRequired
  }
}

// 经办人类型变化处理
const handleAssigneeTypeChange = (value) => {
  // 可以根据不同的经办人类型设置默认值
  if (value === '指定人员') {
    stepForm.assigneeValue = '自动分配'
  } else if (value === '角色') {
    stepForm.assigneeValue = '服务台'
  } else if (value === '部门') {
    stepForm.assigneeValue = '技术支持组'
  }
}

// 提交流转环节配置表单
const submitStepForm = async () => {
  try {
    await stepFormRef.value.validate()

    const isAdd = stepDialog.mode === 'add'
    const api = isAdd ? addWorkflowStep : updateWorkflowStep

    await api(stepForm)
    ElMessage.success('操作成功')
    stepDialog.visible = false

    // 重新加载当前模板的流转环节
    if (currentTemplate.value) {
      fetchWorkflowSteps(currentTemplate.value.templateId)
    }
  } catch (error) {
    console.error('保存流转环节配置失败:', error)
  }
}

// 删除流转环节配置
const deleteStep = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该流转环节吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteWorkflowStep(id)
    ElMessage.success('删除成功')

    // 重新加载当前模板的流转环节
    if (currentTemplate.value) {
      fetchWorkflowSteps(currentTemplate.value.templateId)
    }
  } catch (error) {
    console.error('删除流转环节失败:', error)
  }
}
</script>

<style scoped>
.app-container {}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.mb-2 {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 10px;
}

.template-scroll {
  height: 800px;
  overflow-y: auto;
}

.template-item {
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 4px;
  cursor: pointer;
  background-color: #fff;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.template-item:hover {
  border-color: #409eff;
}

.template-item.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.template-name {
  font-weight: bold;
  margin-bottom: 5px;
}
</style>